//
//  CJComposeViewController.swift
//  SinaWeibo
//
//  Created by 程建 on 16/10/6.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit
import SVProgressHUD

class CJComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        //设置背景颜色
        self.view.backgroundColor = UIColor.white
        
        setNavBar()
        
        setTextView()
        
        setToolBar()
        
        registerNotification()
        
        setSelectPicView()
        
        self.view.bringSubview(toFront: toolBar)
    }
    
    @objc internal func close() {
        dismiss(animated: true, completion: nil)
    }
    
    //视图将要显示的时候
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if selectePicVC.images.count != 0 {
        
            selectePicVC.view.isHidden = false
        }
    }
    
    
    
    private func registerNotification() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChange(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
    }
    
    //键盘弹出或者收起的时候系统会发出响应的通知
    @objc private func keyboardWillChange(n:Notification) {
        //print(n)
        
        //需要 UIKeyboardFrameEndUserInfoKey 这个key 对应的键盘运动结束之后的frame
        //自定中不能够直接存放结构体对象
        let endFrame = (n.userInfo!["UIKeyboardFrameEndUserInfoKey"] as! NSValue).cgRectValue
        
        //更新toolBar的底部约束
        let offSetY = -ScreenHeight + endFrame.origin.y
        toolBar.snp.updateConstraints { (make) in
            make.bottom.equalTo(offSetY)
        }
        UIView.animate(withDuration: 0.25) { 
            self.view.layoutIfNeeded()
        }
        
    }
    
    
    internal lazy var sendBtn: UIBarButtonItem = {
        
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        //设置文字颜色
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
    
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        let barButtonItem = UIBarButtonItem(customView: btn)
        
        barButtonItem.isEnabled = false
        
        return barButtonItem
        
    }()
    
    @objc private func sendBtnDidClick() {
        
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        //在数组和字典中不能够直接添加隐式的可选类型
        let parameters = ["access_token":CJUserAccountViewModel.shardAccountViewModel.userAccount?.access_token ?? "","status" : textView.text ?? ""]
        
        if selectePicVC.images.count == 0 {
    
            //文本微博
            CJNetworkTools.sharedTools.request(method: .POST, urlString: urlString, parameters: parameters) { (_, error) in
                if error != nil {
                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
                    return
                }
                SVProgressHUD.showSuccess(withStatus: "发布微博成功,棒棒哒!")
            }
        }else {
            //图片微博
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            CJNetworkTools.sharedTools.post(urlString, parameters: parameters, constructingBodyWith: { (formdata) in
                //需要将上传的二进制文件拼接到formdata
                /*
                 1. withFileData 需要上传的文件的二进制数据
                 2. name: 服务器接收的字段  'pic'
                 3. fileName: 服务器存储的名称  传或者不传 无所谓 新浪微博有自己的一套文件命名规则
                 4. mimeType 上传的文件的类型  application/octet-stream 忽略文件类型
                 */
                let imageData = UIImagePNGRepresentation(self.selectePicVC.images.last!)
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "dasdas", mimeType: "application/octet-stream")
                
                }, progress: nil, success: { (_, _) in
                    print("成功")
                    SVProgressHUD.showSuccess(withStatus: "发布图片微博成功,棒棒哒!")
                }, failure: { (_, error) in
                    print(error)
                    SVProgressHUD.showError(withStatus: "发布微博失败,请检查网络")
            })
            
        }
        
        
    }

    //懒加载textView
    internal lazy var textView:UITextView = {
    
        let tv = UITextView()
        
        tv.backgroundColor = UIColor.red
        
       // tv.text = "听说下雨天音乐跟辣条跟配哟"
       
        tv.textColor = UIColor.darkGray
        
        tv.font = UIFont.systemFont(ofSize: 16)
        
        tv.delegate = self
        
        //开启垂直方向可以滚动
        tv.alwaysBounceVertical = true
        
        return tv
        
    }()
    
    //设置占位文本
    internal lazy var placeHolderLabel:UILabel = UILabel(title: "听说下雨天音乐跟辣条跟配哟", textColor: UIColor.lightGray, fontSize: 16)
    
    //设置底部工具条
    internal lazy var toolBar: UIToolbar = {
       
        let tool = UIToolbar()
        
        var items = [UIBarButtonItem]()
        //添加5个按钮
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        
        for value in imageNames.enumerated() {
        
            let btn = UIButton()
            
            btn.setImage(UIImage(named: value.element), for: .normal)
            
            btn.setImage(UIImage(named: value.element + "_highlighted"), for: .highlighted)
            
            //设置索引
            btn.tag = value.offset
            
            //添加点击事件
            btn.addTarget(self, action: #selector(statueTypeBtnDidClick(btn:)), for: .touchUpInside)
            btn.sizeToFit()
            
            let barItem = UIBarButtonItem(customView: btn)
            //添加到数组里
            items.append(barItem)
            
            //添加等宽弹簧
            let space = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.flexibleSpace, target: nil, action: nil)
            items.append(space)
            
        }
        items.removeLast()
        tool.items = items
        return tool
    }()
    
    
    @objc private func statueTypeBtnDidClick(btn:UIButton) {
        
        switch btn.tag {
        case 0:
           // print("发布图片")
            //手动调用协议方法
            selectePicVC.userWillAddPic()
        case 1:
            print("@某人")
        case 2:
            print("发布话题")
        case 3:
           // print("发送表情")
            //使用自定义键盘
            //使用自定义键盘使用inputView
            //系统键盘已经是第一响应者是无法进行替换的
            //当输入视图是系统键盘的时候 inputView的值为nil  为nil的情况下系统会自动弹出系统键盘
            if !textView.isFirstResponder {
                //不是第一响应者
                //成为第一响应者
                textView.becomeFirstResponder()
            }
            
            textView.inputView = (textView.inputView == nil ? keyboardView : nil)
            textView.reloadInputViews()
        case 4:
            print("更多")
        default:
            print("瞎点")
        }
    }
    
    //表情键盘视图声明为属性
    lazy var keyboardView:CJEmoticonKeyboardView = {
        
        let keyboard = CJEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: emoticonKeyboardHeight))
        
        return keyboard
    }()
    
    
    //图片选择控制器
    lazy var selectePicVC:CJPicSelectViewController = {
        
        let layout = UICollectionViewFlowLayout()
        //设置间距
        layout.minimumLineSpacing = selectCellMargin
        layout.minimumInteritemSpacing = selectCellMargin
        layout.itemSize = CGSize(width: itemW, height: itemW)
        layout.sectionInset = UIEdgeInsets(top: selectCellMargin, left: selectCellMargin, bottom: 0, right: selectCellMargin)
        
        let selecteVC = CJPicSelectViewController(collectionViewLayout: layout)
        
        //UICollectionViewController的根视图和UICollectionView不是同一个视图
        selecteVC.collectionView?.backgroundColor = UIColor.white
        
        return selecteVC
        
    }()

    
    
    deinit {
        //移除通知
        NotificationCenter.default.removeObserver(self)
    }
}

extension CJComposeViewController:UITextViewDelegate {
    //文本输入框一旦产生变化就得到响应
    func textViewDidChange(_ textView: UITextView) {
        
        //1.设置发送按钮的交互
        self.sendBtn.isEnabled = textView.hasText
        
        //2.设置占位文本框的隐藏状态
        self.placeHolderLabel.isHidden = textView.hasText
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        textView.resignFirstResponder()
    }
    
}

//MARK:设置ui界面相关的方法
extension CJComposeViewController {
    
    internal func setNavBar() {
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", imageName: nil, target: self, action: #selector(close))
        
        //自定义titleView
        let titleLabel = UILabel(title: "", textColor: UIColor.darkGray, fontSize: 16)
        var titleText = "发布微博"
        titleLabel.numberOfLines = 0
        titleLabel.textAlignment = .center
        if let name = CJUserAccountViewModel.shardAccountViewModel.userAccount?.name {
            //不为空
            titleText = "发布微博\n\(name)"
            //通过富文本修改文字的字体和颜色
            //1. 实例化一个可变的(才能够添加属性)属性文本
            let strM = NSMutableAttributedString(string: titleText)
            let range = (titleText as NSString).range(of: name)
            //给可变的属性字符串添加属性
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: range)
            //设置属性字符串
            titleLabel.attributedText = strM
        }else {
            //为空  设置一个相同属性的文字即可
            titleLabel.text = titleText
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
        //设置发送微博按钮
        self.navigationItem.rightBarButtonItem = sendBtn
        
    }
    
    
    internal func setTextView() {
        
        self.view.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.top.left.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3)
        }
        
        textView.addSubview(placeHolderLabel)
        placeHolderLabel.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(8)
            make.left.equalTo(textView).offset(5)
            
        }
        
    }
    
    internal func setToolBar() {
        
        self.view.addSubview(toolBar)
        toolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(36)
        }
        
    }
    
    
    internal func setSelectPicView() {
        
        //先添加子视图控制器 ,为了保证在modal界面的时候 selectePicVC不会被释放掉
        self.addChildViewController(selectePicVC)
        self.view.addSubview(selectePicVC.view)
        
        //设置约束
        selectePicVC.view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3 * 2 )
        }
        
        selectePicVC.view.isHidden = true
        
    }

    

}


